import json
import sys
sys.path.append("../../")

from model.StockBaseInfo import *
from model.CommonDb import *
from controller.MsgController import *
from prettytable import PrettyTable
from operator import itemgetter
from model.CodesModel import *
from frameworks.utils.RedisUtil import *
import datetime
import pandas as pd
import time

class ParseStockController:
    def __init__(self,args):
        self.args = args
        self.service = StockBaseInfo()
        self.today = datetime.datetime.now().strftime("%Y-%m-%d")
        self.msg = MsgController()
        self.msgcon = MsgController()
        self.codeModel = CodesModel()

    def run(self):
        if self.args["func"] == "pre_warning":
            return self.execParse(self.args)

    """
    获取每日行业的净收入
    """
    def execParse(self,args):
        db = CommonDb("zhangting_bk","sto")
        db1 = CommonDb("codes", "sto")
        rs = db.getAllData("*","1")
        base = StockBaseInfo()
        lastColumns = []
        redis = RedisUtil()
        for row in rs:
            newdata = []
            code = row["code"][2:]
            code = "300364"
            info = self.codeModel.getStockInfo(code)
            key = "lines_" + code
            """
            print(key)
            linedata = base.getDfcfLineDay(code, 60)
            redis.vset(key, json.dumps(linedata))
            time.sleep(2)
            continue
            """
            redisData = redis.vget(key)
            linedata = json.loads(redisData)
            if redisData == None:
                linedata = base.getDfcfLineDay(code, 60)
                redis.vset(key,json.dumps(linedata))
            for line in linedata["klines"]:
                newdata.append(line.split(","))
            df = pd.DataFrame(newdata,columns=["date","open","close","high","low","volnum","money","zhengfu","zhangfu","zhangdiee","huanshoulv"])
            df["ma5"] = df["close"].rolling(5).mean()
            df["valma5"] = df["volnum"].rolling(5).mean()
            df["ma10"] = df["close"].rolling(10).mean()
            df["ma20"] = df["close"].rolling(20).mean()
            df["ma30"] = df["close"].rolling(30).mean()
            df.set_index("date",inplace=True)
            redcnt = 0
            donwcnt = 0
            n = 0
            lastval = 0
            allredcnt = 0
            tb = PrettyTable()
            tb.field_names = ['日期', '代码', '代码名称', '传统行业', '30天红天数', '价格连续上涨天数',
                              '价格连续下跌天数', '价格预警', '成交量连续上涨天数', '成交量连续下跌天数', "成交量预警",
                              "振幅预警"]
            for index,option in df.iterrows():
                if n < 31:
                    n += 1
                    lastval = option["volnum"]
                    continue

                if float(option["zhangfu"]) >= 0:
                    redcnt += 1
                    donwcnt = 0
                    allredcnt += 1
                else:
                    redcnt = 0
                    donwcnt += 1
                columns = [index, info[0]["code"], info[0]["codename"], info[0]["industry"], allredcnt]
                if float(option["close"]) >= float(option["open"]):
                    sunstr = "，收阳线"
                else:
                    sunstr = "，收阴线"
                if float(option["zhangfu"]) >= 0 and redcnt > 2:
                    columns.append(redcnt)
                    columns.append(donwcnt)
                    if sunstr == "，收阴线":
                        sunstr += "，可能转为跌势"
                    columns.append("上涨预警"+sunstr)
                elif float(option["zhangfu"]) >= 0 and redcnt > 0:
                    columns.append(redcnt)
                    columns.append(donwcnt)
                    if sunstr == "，收阴线":
                        sunstr += "，可能转为跌势"
                    columns.append("连续上涨"+sunstr)
                elif float(option["zhangfu"]) < 0 and donwcnt > 1:
                    columns.append(redcnt)
                    columns.append(donwcnt)
                    if sunstr == "，收阳线":
                        sunstr += "，可能转为涨势"
                    columns.append("下跌预警"+sunstr)
                elif float(option["zhangfu"]) < 0:
                    columns.append(redcnt)
                    columns.append(donwcnt)
                    if sunstr == "，收阳线":
                        sunstr += "，可能转为涨势"
                    columns.append("连续下跌"+sunstr)
                valrate = round((float(option["volnum"])-float(lastval))/float(lastval),2)
                upvalcnt = 0
                downvalcnt = 0
                if valrate >= 0:
                    upvalcnt += 1
                    downvalcnt = 0
                else:
                    upvalcnt = 0
                    downvalcnt += 1
                if valrate > 2:
                    columns.append(upvalcnt)
                    columns.append(downvalcnt)
                    columns.append("上涨" + str(valrate) + "倍，上涨预警")
                elif valrate >= 0:
                    columns.append(upvalcnt)
                    columns.append(downvalcnt)
                    columns.append("上涨" + str(valrate) + "倍")
                elif valrate < -0.2:
                    columns.append(upvalcnt)
                    columns.append(downvalcnt)
                    columns.append("下跌" + str(valrate) + "倍，下跌预警")
                elif valrate < 0:
                    columns.append(upvalcnt)
                    columns.append(downvalcnt)
                    columns.append("下跌" + str(valrate) + "倍")
                lastval = option["volnum"]
                comment = ""
                if float(option["zhengfu"]) > 8 and float(option["open"]) > float(option["close"]):
                    comment += "振幅异常"
                if float(option["zhangfu"]) > 9.8:
                    comment += "价格涨停"
                elif float(option["zhangfu"]) > 6:
                    comment += "价格大涨"
                elif float(option["zhangfu"]) > 3:
                    comment += "价格小涨"
                elif float(option["zhangfu"]) < -9:
                    comment += "价格跌停"
                elif float(option["zhangfu"]) < -6:
                    comment += "价格大跌"
                elif float(option["zhangfu"]) < -6:
                    comment += "价格小跌"
                columns.append(comment + str(float(option["zhangfu"])) + "%")
                tb.add_row(columns)
                n += 1
            print(tb)
            break

